package inet.app.view.fragment;

import inet.app.R;
import inet.app.common.XoSoConstants;
import inet.app.controller.connect.MasterConnector;
import inet.app.controller.database.DataBaseHandler;
import inet.app.controller.parser.Parser_Kqxs;
import inet.app.controller.request.Request;
import inet.app.model.object.KqGiaiRegion;
import inet.app.model.object.KqGiai_Item;
import inet.app.model.object.SubKq_Item;
import inet.app.model.util.AsyncTaskExecutor;
import inet.app.model.util.DateProc;
import inet.app.model.util.SmartLog;
import inet.app.model.util.Util;
import inet.app.view.activity.LichMoThuongFragment;
import inet.app.view.activity.MyApp;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.Time;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class FragmentMT extends BaseFragmentKQ implements OnClickListener,
		OnTouchListener, OnPreparedListener, OnCompletionListener {
	private boolean isReplay = false;
	private int countMe = 0;
	private String counter_save;
	private TextView tvDate, tvTrucTiep;
	private Spinner spTinh;
	private TextView tvSpinner;
	private int onehit = 0;
	private Button bt_thongke;
	private String region;
	private int myYear, myMonth, myDay;
	public MasterConnector master;
	private String code1 = "", code2 = "", code3 = "";
	private Parser_Kqxs parser = new Parser_Kqxs();
	private Request request = new Request();
	private ArrayList<KqGiai_Item> push = new ArrayList<KqGiai_Item>();
	private ArrayList<KqGiai_Item> arraylist = new ArrayList<KqGiai_Item>();
	private ArrayList<KqGiai_Item> arraylist_end = new ArrayList<KqGiai_Item>();
	private ArrayList<String> list_matinh = new ArrayList<String>();
	private ArrayList<String> list_tentinh = new ArrayList<String>();
	private Hashtable<String, KqGiai_Item> hashtable_result = new Hashtable<String, KqGiai_Item>();
	private String nhamang = "", cuoc = " (Cước 1000đ)",
			title_click = "CLICK NHẬN KQXS ";
	private DataBaseHandler db;
	private SubKq_Item item_subkq;
	private boolean isSendSms = false;
	private int dayofmonth;
	private int sotinh = 0;
	// MEDIA
	private AssetManager assets;
	private int countclick = 0;
	private String data[];
	private String databuf[] = { ".....-....." };
	private String rngay = null, rthang = null, rgiaidb = null, rgiai1 = null,
			rgiai2 = null, rgiai3 = null, rgiai4 = null, rgiai5 = null,
			rgiai6 = null, rgiai7 = null, rgiai8 = null;
	private int thuofngay;
	private AsyncTask<Void, Void, Void> mLoadKQXSServerTask;
	private MyNetworkTask myTask;
	private KqGiai_Item item = new KqGiai_Item("", " TƯỜNG THUẬT", "", ".....",
			".....", ".....", "..... - .....",
			"..... - ..... - ..... - ..... - ..... - ..... - .....", ".....",
			"..... - ..... - .....", ".....", ".....");

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString("DO NOT CRASH", "OK");
	}

	public static Fragment newInstance(Context context) {
		FragmentMT f = new FragmentMT();
		return f;
	}

	public static Fragment newInstance(Context context, String position) {
		FragmentMT f = new FragmentMT();
		Bundle args = new Bundle();
		args.putString("pos", position);
		f.setArguments(args);
		return f;
	}

	public static Fragment newInstance(Context context, String position,
			String json) {
		FragmentMT f = new FragmentMT();
		Bundle args = new Bundle();
		args.putString("pos", position);
		args.putString("json", json);
		f.setArguments(args);
		return f;
	}

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		root = (ViewGroup) inflater.inflate(R.layout.ketqua_detail, null);
		// SETUP SUB
		tvTrucTiep = (TextView) root.findViewById(R.id.tvTrucTiep);

		if (Util.onLiveTimeMT()) {
			tvTrucTiep.setVisibility(View.VISIBLE);
			tvTrucTiep.setText(R.string.tvTTMT);
		} else {
			tvTrucTiep.setVisibility(View.GONE);
		}
		// Gét nhà mạng
		nhamang = Util.getSharePreferences(getActivity());
		if (nhamang.contains("VIETTEL")) {
			if (Util.onClick_MT()) {
				cuoc = " (Cước 5000đ)";
				title_click = "CLICK NHẬN KQTT ";
			} else {
				cuoc = " (Cước 1000đ)";
				title_click = "CLICK NHẬN KQXS ";
			}
		} else {
			cuoc = " (Cước 2000đ)";
		}
		System.out.println("NHA MNG MIEN TRUNG " + nhamang);

		// END SUB
		webView = (WebView) root.findViewById(R.id.webView);
		bt_thongke = (Button) root.findViewById(R.id.bt_LichMoThuong);
		tvDate = (TextView) root.findViewById(R.id.tvDate);
		imgPlay = (ImageButton) root.findViewById(R.id.imgPlay);
		spTinh = (Spinner) root.findViewById(R.id.sptinh);
		tvSpinner = (TextView) root.findViewById(R.id.tvSpinner);
		tvSpinner.setVisibility(View.VISIBLE);
		tvSpinner.setOnClickListener(this);

		// Setup webview
		webView.setWebViewClient(new MyWebViewClient());
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		webView.getSettings().setSupportMultipleWindows(true);
		webView.getSettings().setSupportZoom(false);
		webView.setVerticalScrollBarEnabled(true);
		webView.setHorizontalScrollBarEnabled(false);

		// Set onListener
		imgPlay.setOnClickListener(this);
		tvDate.setOnTouchListener(this);
		spTinh.setOnTouchListener(this);
		bt_thongke.setOnClickListener(this);

		// Set Date, Day, Month, Year
		date_current = DateProc.Timestamp2DDMMYYYY(DateProc.createTimestamp());
		if (Util.onBeforeLiveTimeMT()) {
			date_current = DateProc.TimestampPlusDay2DDMMYYYY(
					DateProc.createTimestamp(), -1);
		}

		// SET DATE CURRENT
		tvDate.setText(" Ngày " + date_current);

		myYear = Integer.parseInt(date_current.split("/")[2]);
		myMonth = Integer.parseInt(date_current.split("/")[1]);
		myDay = Integer.parseInt(date_current.split("/")[0]);

		// Get Position
		if (getArguments() != null) {
			// pos = getArguments().getString("pos");
			// json = getArguments().getString("json");
		}
		region = "MT";
		Update();
		spTinh.setVisibility(View.VISIBLE);

		bt_thongke.setText("Lịch Mở Thưởng");
		// -------------------------------SET UP
		// MEDIAPLAYER--------------------------//
		media = new MediaPlayer();
		media.setOnPreparedListener(this);
		media.setOnCompletionListener(this);
		assets = getActivity().getAssets();

		Calendar cal = Calendar.getInstance();
		thuofngay = cal.get(Calendar.DAY_OF_WEEK);
		System.out.println("THU OF NAY LA " + thuofngay);
		if (Util.onAfterLiveTimeMT()) {
			System.out.println("CHAY VAO ONLIVE");
			if (thuofngay == 5 || thuofngay == 7) {
				sotinh = 3;
				System.out.println("TINH 3");
			} else {
				System.out.println("tinh 2");
				sotinh = 2;
			}
		} else {
			if (thuofngay == 6 || thuofngay == 1) {
				sotinh = 3;
			} else {
				sotinh = 2;
			}
		}
		System.out.println("SÔ tinh là  " + sotinh);
		mCode = "MT";
		return root;

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		System.out.println("CHAY VAO DAY ROI NHE");
	}

	private void AddSpinner() {
		ArrayAdapter<String> arrayadapter_sptinh = new ArrayAdapter<String>(
				getActivity(), android.R.layout.simple_spinner_item,
				list_tentinh);
		arrayadapter_sptinh
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spTinh.setAdapter(arrayadapter_sptinh);
		if (list_matinh != null && list_matinh.size() > 0) {
			matinh = list_matinh.get(0);
		}
		spTinh.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View v,
					final int pos, long id) {
				tvSpinner.setText(" " + list_tentinh.get(pos));
				resetAudio();
				listaudio.clear();
				spTinh.setSelection(pos);
				matinh = list_matinh.get(pos);
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
	}

	private void load_data_webviewTN(List<KqGiai_Item> arraylist,
			String numberCurrent) {
		webView.clearCache(true);
		String htmlKetqua = "";
		String giaidb, giai1, giai2, giai5, giai7, giai8;
		String[] giai3 = null;
		String[] giai4 = null;
		String[] giai6 = null;
		String buttonSms = "";
		itemsReading = arraylist;
		for (int i = 0; i < arraylist.size(); i++) {
			SmartLog.d("matinh = " + matinh + ", current = "
					+ arraylist.get(i).getCode() + ", numberCurrent = "
					+ numberCurrent);
			boolean isTinhCurrent = arraylist.get(i).getCode().equals(matinh);
			arraylist.get(i).getId();
			if (arraylist.get(i).getGiaidb().equals(""))
				giaidb = ".....";
			else
				giaidb = arraylist.get(i).getGiaidb();

			if (arraylist.get(i).getGiai1().equals(""))
				giai1 = ".....";
			else
				giai1 = arraylist.get(i).getGiai1();

			if (arraylist.get(i).getGiai2().equals(""))
				giai2 = ".....";
			else
				giai2 = arraylist.get(i).getGiai2();

			if (arraylist.get(i).getGiai5().equals(""))
				giai5 = ".....";
			else
				giai5 = arraylist.get(i).getGiai5();

			if (arraylist.get(i).getGiai7().equals(""))
				giai7 = ".....";
			else
				giai7 = arraylist.get(i).getGiai7();

			if (arraylist.get(i).getGiai8().equals(""))
				giai8 = ".....";
			else
				giai8 = arraylist.get(i).getGiai8();

			giai3 = (arraylist.get(i).getGiai3() + "-.....-.....-").split("-");
			giai4 = (arraylist.get(i).getGiai4() + "-.....-.....-.....-.....-.....-.....-.....-")
					.split("-");
			giai6 = (arraylist.get(i).getGiai6() + "-.....-.....-.....-")
					.split("-");

			if (!isFree) {
				buttonSms = "<input style=\"background-color:#323232; color:#ffffff; height:30px; width:100%; font-size:11px; font-weight:bold; float:right; position:relative;\" type=\"button\" name=\"desel\" value=\""
						+ title_click
						+ arraylist.get(i).getName()
						+ cuoc
						+ "\" onclick=\"window.location.href='"
						+ arraylist.get(i).getCode() + "'\" >";
			} else {
				buttonSms = "<input style=\"background-color:#323232; color:#ffffff; height:30px; width:100%; font-size:11px; font-weight:bold; float:right; position:relative;\" type=\"button\" name=\"desel\" value=\""
						+ "Kết Quả Xổ Số "
						+ arraylist.get(i).getName()
						+ " - "
						+ arraylist.get(i).getDate() + "\" >";
			}

			htmlKetqua += "<div  style=\"cursor: pointer; background-color:#323232;width: 100%\">"
					+ buttonSms
					+ "</div>"
					+ "<div><table width=\"100%\" border=\"0\" bgcolor=\"#CCCCCC\" cellspacing=\"1\"style=\"text-align:center;\" cellpadding=\"0\">"
					+ " <tr class=\"hienso\"  bgcolor=\"#FFFFFF\" height=\"30\"> <td class=\"left\" width=\"10%\">"
					+ "<img src=\"file:///android_res/drawable/img_g8.png\" width=\"35\" height=\"35\"/>"
					+ "</td>"
					+ " <td class=\"right\" colspan=\"12\" bgcolor="
					+ (giai8.equals(numberCurrent) && isTinhCurrent ? MARK_COLOR
							: "\"#FFFFFF\">")
					+ giai8
					+ "</td> </tr> "
					+ " <tr class=\"hienso\"  bgcolor=\"#FFFFFF\" height=\"30\"> <td class=\"left\">"
					+ "<img src=\"file:///android_res/drawable/img_g7.png\" width=\"35\" height=\"35\"/>"
					+ "</td>"
					+ " <td class=\"right\" colspan=\"12\" bgcolor="
					+ (giai7.equals(numberCurrent) && isTinhCurrent ? MARK_COLOR
							: "\"#FFFFFF\">")
					+ giai7
					+ "</td> </tr> "
					+ "<tr class=\"hienso\"  bgcolor=\"#FFFFFF\" height=\"30\"> <td class=\"left\">"
					+ "<img src=\"file:///android_res/drawable/img_g6.png\" width=\"35\" height=\"35\"/>"
					+ "</td>"
					+ "<td class=\"right\" width=\"35%\" colspan=\"4\" bgcolor="
					+ (giai6[0].equals(numberCurrent) && isTinhCurrent ? MARK_COLOR
							: "\"#FFFFFF\">")
					+ giai6[0]
					+ "</td> <td class=\"right\" width=\"35%\"colspan=\"4\" bgcolor="
					+ (giai6[1].equals(numberCurrent) && isTinhCurrent ? MARK_COLOR
							: "\"#FFFFFF\">")
					+ giai6[1]
					+ "</td> <td class=\"right\" width=\"35%\"colspan=\"4\" bgcolor="
					+ (giai6[2].equals(numberCurrent) && isTinhCurrent ? MARK_COLOR
							: "\"#FFFFFF\">")
					+ giai6[2]
					+ "</td> </tr> "
					+ " <tr class=\"hienso\"  bgcolor=\"#FFFFFF\" height=\"30\"> <td class=\"left\">"
					+ "<img src=\"file:///android_res/drawable/img_g5.png\" width=\"35\" height=\"35\"/>"
					+ "</td>"
					+ "<td class=\"right\" colspan=\"12\" bgcolor="
					+ (giai5.equals(numberCurrent) && isTinhCurrent ? MARK_COLOR
							: "\"#FFFFFF\">")
					+ giai5
					+ "</td> </tr>"
					+ " <tr class=\"hienso\"  bgcolor=\"#FFFFFF\" height=\"30\"> <td class=\"left\" rowspan=\"2\">"
					+ "<img src=\"file:///android_res/drawable/img_giai4.png\" width=\"35\" height=\"70\"/>"
					+ "</td>"
					+ " <td class=\"right\" width=\"25%\"colspan=\"3\" bgcolor="
					+ (giai4[0].equals(numberCurrent) && isTinhCurrent ? MARK_COLOR
							: "\"#FFFFFF\">")
					+ giai4[0]
					+ "</td> <td class=\"right\" colspan=\"3\" width=\"25%\" bgcolor="
					+ (giai4[1].equals(numberCurrent) && isTinhCurrent ? MARK_COLOR
							: "\"#FFFFFF\">")
					+ giai4[1]
					+ "</td> <td class=\"right\" colspan=\"3\" width=\"25%\" bgcolor="
					+ (giai4[2].equals(numberCurrent) && isTinhCurrent ? MARK_COLOR
							: "\"#FFFFFF\">")
					+ giai4[2]
					+ "</td> <td class=\"right\" colspan=\"3\" width=\"25%\" bgcolor="
					+ (giai4[3].equals(numberCurrent) && isTinhCurrent ? MARK_COLOR
							: "\"#FFFFFF\">")
					+ giai4[3]
					+ "</td> </tr> "
					+ " <tr class=\"hienso\"  bgcolor=\"#FFFFFF\" height=\"30\"> <td class=\"right\" colspan=\"4\" width=\"30%\" bgcolor="
					+ (giai4[4].equals(numberCurrent) && isTinhCurrent ? MARK_COLOR
							: "\"#FFFFFF\">")
					+ giai4[4]
					+ "</td> <td class=\"right\" colspan=\"4\" width=\"30%\" bgcolor="
					+ (giai4[5].equals(numberCurrent) && isTinhCurrent ? MARK_COLOR
							: "\"#FFFFFF\">")
					+ giai4[5]
					+ "</td> <td class=\"right\" colspan=\"4\" width=\"30%\" bgcolor="
					+ (giai4[6].equals(numberCurrent) && isTinhCurrent ? MARK_COLOR
							: "\"#FFFFFF\">")
					+ giai4[6]
					+ "</td> </tr> "
					+ " <tr class=\"hienso\"  bgcolor=\"#FFFFFF\" height=\"30\"> <td class=\"left\">"
					+ "<img src=\"file:///android_res/drawable/img_g3.png\" width=\"35\" height=\"35\"/>"
					+ "</td>"
					+ " <td class=\"right\" colspan=\"6\" width=\"50%\" bgcolor="
					+ (giai3[0].equals(numberCurrent) && isTinhCurrent ? MARK_COLOR
							: "\"#FFFFFF\">")
					+ giai3[0]
					+ "</td> <td class=\"right\" colspan=\"6\" width=\"50%\" bgcolor="
					+ (giai3[1].equals(numberCurrent) && isTinhCurrent ? MARK_COLOR
							: "\"#FFFFFF\">")
					+ giai3[1]
					+ "</td> </tr>"
					+ " <tr class=\"hienso\"  bgcolor=\"#FFFFFF\" height=\"30\"> <td class=\"left\">"
					+ "<img src=\"file:///android_res/drawable/img_g2.png\" width=\"35\" height=\"35\"/>"
					+ "</td>"
					+ " <td class=\"right\" colspan=\"12\" bgcolor="
					+ (giai2.equals(numberCurrent) && isTinhCurrent ? MARK_COLOR
							: "\"#FFFFFF\">")
					+ giai2
					+ "</td> </tr> "
					+ " <tr class=\"hienso\"  bgcolor=\"#FFFFFF\" height=\"30\"> <td class=\"left\">"
					+ "<img src=\"file:///android_res/drawable/img_g1.png\" width=\"35\" height=\"35\"/>"
					+ "</td>"
					+ " <td class=\"right\" colspan=\"12\" bgcolor="
					+ (giai1.equals(numberCurrent) && isTinhCurrent ? MARK_COLOR
							: "\"#FFFFFF\">")
					+ giai1
					+ "</td> </tr> "
					+ " <tr class=\"hienso\"  bgcolor=\"#FFFFFF\" height=\"30\"> <td class=\"left\">"
					+ "<img src=\"file:///android_res/drawable/img_db.png\" width=\"35\" height=\"35\"/>"
					+ "</td>"
					+ " <td class=\"right\" style=\"color:red;\"colspan=\"12\" bgcolor="
					+ (giaidb.equals(numberCurrent) && isTinhCurrent ? MARK_COLOR
							: "\"#FFFFFF\">")
					+ giaidb
					+ "</td> </tr>"
					+ "</table></div>";
		}
		webView.loadDataWithBaseURL("file:///android_asset/", XoSoConstants.css
				+ htmlKetqua + "</body></html>", "text/html", "utf-8", null);
	}

	public boolean isNull() {
		if (arraylist == null && push == null)
			return true;
		else
			return false;
	}

	public void isOnKeyBack() {
		if (media != null)
			media.stop();
		dangnghe = false;
	}

	public void Update() {
		// check kqmt from db
		KqGiaiRegion ketQuaMT = mDbManager.getDaoKqXSRegion().selectRow(
				date_current, region);
		if (ketQuaMT != null && !Util.onLiveTime_MT()) {
			// load kqmt from db
			SmartLog.d("load kqmt " + date_current + " from db");
			arraylist = mDbManager.getDaoKQGiaiXS().selectRowByRegion(
					ketQuaMT.getId());
			fillDataToView();
		} else {
			// load from server
			SmartLog.d("load kqmt " + date_current + " from server");
			if (myTask != null) {
				return;
			}
			myTask = new MyNetworkTask();
			AsyncTaskExecutor.executeConcurrently(myTask);
		}
	}

	private class MyNetworkTask extends AsyncTask<Void, Integer, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showLoading(true);
		}

		@Override
		protected Void doInBackground(Void... params) {
			arraylist = parser.getList(request.getkqxsbyregion(date_current,
					region));
			if (arraylist != null && !Util.onLiveTime_MT()) {
				// update result to database
				SmartLog.d("save kqmt " + date_current + " to server");
				KqGiaiRegion ketQuaMT = new KqGiaiRegion();
				ketQuaMT.setDate(date_current);
				ketQuaMT.setRegion(region);
				int regionId = (int) mDbManager.getDaoKqXSRegion().insertRow(
						ketQuaMT);
				if (regionId != -1) {
					for (KqGiai_Item item : arraylist) {
						item.setRegionId(regionId);
					}
					mDbManager.getDaoKQGiaiXS().insertCollection(arraylist);
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPreExecute();
			showLoading(false);
			fillDataToView();
		}
	}

	private void fillDataToView() {
		if (arraylist != null) {
			if (Util.onNullMT()) {
				push.add(item);
				push.add(item);
				load_data_webviewTN(push, "");
			} else {
				load_data_webviewTN(arraylist, "");
			}

			if (Util.onLiveTime_MT()) {
				Macodebydate_Live();
			} else {
				Macodebydate();
			}
			AddSpinner();
			bt_thongke.setVisibility(View.VISIBLE);
		} else {
			webView.clearCache(true);
			webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
			bt_thongke.setVisibility(View.GONE);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.imgPlay:
			Util.writeFilePrivateTab(String.valueOf("1"), getActivity());
			countclick++;
			if (media != null) {
				try {
					if (push.size() > 0) {
						SmartLog.d("read audio from push");
						boolean isPlay = getArrayAudio(push);
						if (!isPlay) {
							getArrayAudio(arraylist);
						}
					} else {
						SmartLog.d("read audio from http");
						getArrayAudio(arraylist);
					}

					if (media.isPlaying()) {
						pauseAudio();
					} else {
						resumeAudio();
					}

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			break;
		case R.id.bt_LichMoThuong:
			Intent intentLmt = new Intent(getActivity(),
					LichMoThuongFragment.class);
			Bundle rb = new Bundle();
			rb.putString("REGION", region);
			intentLmt.putExtras(rb);
			startActivity(intentLmt);
			MyApp.lastPosition = XoSoConstants.posMoThuong;
			break;
		case R.id.tvSpinner:
			spTinh.performClick();
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN)
			switch (v.getId()) {
			case R.id.tvDate:
				DatePickerDialog.OnDateSetListener myOnDateListener = new DatePickerDialog.OnDateSetListener() {
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						webView.clearView();
						webView.requestLayout();
						resetAudio();

						// FORMAT DATE
						myYear = year;
						myMonth = monthOfYear + 1;
						myDay = dayOfMonth;
						SimpleDateFormat form1 = new SimpleDateFormat(
								"dd/MM/yyyy");
						java.sql.Timestamp ts1 = DateProc.buildTimestamp(
								myYear, myMonth, myDay);
						date_current = form1.format(ts1);
						tvDate.setText(" Ngày " + date_current);
						sendrequest(date_current, region);
					}
				};
				DatePickerDialog datepicker = new DatePickerDialog(
						getActivity(), myOnDateListener, myYear, myMonth - 1,
						myDay);
				datepicker.show();
				break;
			default:
				break;
			}
		return false;
	}

	private void sendrequest(String date, String code) {
		SmartLog.d("request MT date " + date);
		KqGiaiRegion region = mDbManager.getDaoKqXSRegion().selectRow(date,
				code);
		if (region != null && !Util.onLiveTime_MT()) {
			// load from db
			SmartLog.d("request MT date " + date + " to db");
			arraylist = mDbManager.getDaoKQGiaiXS().selectRowByRegion(
					region.getId());
			fillDataToViewFromSendRequest();
		} else {
			SmartLog.d("request MT date " + date + " to server");
			sendRequestToServer(date, code);
		}

	}

	private void sendRequestToServer(final String date, final String code) {
		SmartLog.d("load xsmt " + date + " from server");
		if (mLoadKQXSServerTask != null) {
			return;
		}
		mLoadKQXSServerTask = new AsyncTask<Void, Void, Void>() {

			@Override
			protected void onPreExecute() {
				showLoading(true);
			}

			@Override
			protected Void doInBackground(Void... params) {

				arraylist = parser.getList(request.getkqxsbyregion(
						date_current, code));

				SmartLog.d("request mt = "
						+ request.getkqxsbyregion(date_current, code));

				if (arraylist != null && arraylist.size() != 0
						&& !Util.onLiveTime_MT()) {
					String dateFromJson = arraylist.get(0).getDate();
					KqGiaiRegion ketQuaMT = null;
					if (!dateFromJson.equals(date)) {
						ketQuaMT = mDbManager.getDaoKqXSRegion().selectRow(
								dateFromJson, code);
						if (ketQuaMT != null) {
							return null;
						}
					}
					// save kq to db
					ketQuaMT = new KqGiaiRegion();
					ketQuaMT.setDate(dateFromJson);
					ketQuaMT.setRegion(code);
					int regionId = (int) mDbManager.getDaoKqXSRegion()
							.insertRow(ketQuaMT);
					if (regionId != -1) {
						for (KqGiai_Item item : arraylist) {
							item.setRegionId(regionId);
						}
						mDbManager.getDaoKQGiaiXS().insertCollection(arraylist);
					}
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void params) {
				mLoadKQXSServerTask = null;
				fillDataToViewFromSendRequest();
				showLoading(false);
			}
		};
		mLoadKQXSServerTask.execute();
	}

	private void fillDataToViewFromSendRequest() {
		if (arraylist != null) {

			date_current = arraylist.get(0).getDate();
			String kk[] = date_current.split("/");
			myDay = Integer.parseInt(kk[0]);
			myMonth = Integer.parseInt(kk[1]);
			myYear = Integer.parseInt(kk[2]);
			tvDate.setText(" Ngày " + date_current);

			Macodebydate();
			AddSpinner();
			imgPlay.setEnabled(true);
			load_data_webviewTN(arraylist, "");
			bt_thongke.setVisibility(View.VISIBLE);
		} else {
			dangnghe = false;
			imgPlay.setEnabled(false);
			imgPlay.setBackgroundResource(R.drawable.button_on_sound);
			if (media.isPlaying())
				media.stop();
			webView.clearCache(true);
			webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
			bt_thongke.setVisibility(View.GONE);
			Util.showDialog(1, getActivity());
		}
	}

	public void Macodebydate() {
		int i;
		list_matinh.clear();
		list_tentinh.clear();
		if (arraylist != null) {
			for (i = 0; i < arraylist.size(); i++) {
				list_matinh.add(arraylist.get(i).getCode());
				list_tentinh.add(arraylist.get(i).getName());
			}
		}
	}

	public void Macodebydate_Live() {
		String date = DateProc.Timestamp2DDMMYYYY(DateProc.createTimestamp());
		String temp[];
		temp = date.split("/");
		final Calendar cal_thu = Calendar.getInstance();
		cal_thu.set(Integer.parseInt(temp[2]), Integer.parseInt(temp[1]) - 1,
				Integer.parseInt(temp[0].substring(temp[0].length() - 2,
						temp[0].length())));
		int thuofngay = cal_thu.get(Calendar.DAY_OF_WEEK);
		list_matinh.clear();
		list_tentinh.clear();
		if (thuofngay == 1) {
			code1 = "XSKH";
			code2 = "XSKT";
			list_matinh.add(code1);
			list_matinh.add(code2);
			list_tentinh.add(" Khánh Hòa");
			list_tentinh.add(" Kon Tum");
		} else if (thuofngay == 7) {
			code1 = "XSDNG";
			code2 = "XSQNI";
			code3 = "XSDNO";
			list_matinh.add(code1);
			list_matinh.add(code2);
			list_matinh.add(code3);
			list_tentinh.add(" Đà Nẵng");
			list_tentinh.add(" Quảng Ngãi");
			list_tentinh.add(" Đắc Nông");
		}

		else if (thuofngay == 6) {
			code1 = "XSGL";
			code2 = "XSNT";
			list_matinh.add(code1);
			list_matinh.add(code2);
			list_tentinh.add(" Gia Lai");
			list_tentinh.add(" Ninh Thuận");

		} else if (thuofngay == 5) {
			code1 = "XSBDH";
			code2 = "XSQB";
			code3 = "XSQT";
			list_matinh.add(code1);
			list_matinh.add(code2);
			list_matinh.add(code3);
			list_tentinh.add(" Bình Định");
			list_tentinh.add(" Quảng Bình");
			list_tentinh.add(" Quảng Trị");
		} else if (thuofngay == 4) {
			code1 = "XSKH";
			code2 = "XSDNG";
			list_matinh.add(code1);
			list_matinh.add(code2);
			list_tentinh.add(" Khánh Hòa");
			list_tentinh.add(" Đà Nẵng");
		} else if (thuofngay == 3) {
			code1 = "XSDLK";
			code2 = "XSQNM";
			list_matinh.add(code1);
			list_matinh.add(code2);
			list_tentinh.add(" Đắc Lăk");
			list_tentinh.add(" Quảng Nam");
		} else if (thuofngay == 2) {
			code1 = "XSPY";
			code2 = "XSTTH";
			list_matinh.add(code1);
			list_matinh.add(code2);
			list_tentinh.add(" Phú Yên");
			list_tentinh.add(" Thừa Thiên Huế");
		}

	}

	@Override
	public void onPrepared(MediaPlayer mp) {
		// TODO Auto-generated method stub
		// Start video
		if (countclick >= 1) {
			if (!media.isPlaying()) {
				media.start();
			}
		}
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		System.out.println("Pos on Completion " + position);
		Time time = new Time();
		time.setToNow();
		if (position <= 112) {
			try {
				Thread.sleep(150);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (dangnghe) {
				media.reset();
				try {
					playAudio();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} else {
			stopAudio();
			position = 0;
			mPreference.setPosAudio(mCode, matinh, date_current, position);
			imgPlay.setBackgroundResource(R.drawable.button_on_sound);
			
			//reset webview
			load_data_webviewTN(itemsReading, "");
		}
	}

	public void Update_Live_TN(ArrayList<KqGiai_Item> push_tn) {
		System.out.println("UPDATE MIEN TRUNG");
		countMe++;
		push = push_tn;
		// GetMediaAudio
		try {
			getArrayAudio(push_tn);
			if (countMe < 2)
				media = new MediaPlayer();
			if (media != null & !media.isPlaying() & isReplay) {
				resumeAudio();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// EndGet
		onehit++;
		if (webView == null) {
			// not yet inflate
			return;
		}
		if (onehit < 2) {
			webView.clearView();
			webView.requestLayout();
			Macodebydate_Live();

			AddSpinner();

			KqGiai_Item item01 = new KqGiai_Item(code1, " TƯỜNG THUẬT", "",
					".....", ".....", ".....", "..... - .....",
					"..... - ..... - ..... - ..... - ..... - ..... - .....",
					".....", "..... - ..... - .....", ".....", ".....");
			KqGiai_Item item02 = new KqGiai_Item(code2, " TƯỜNG THUẬT", "",
					".....", ".....", ".....", "..... - .....",
					"..... - ..... - ..... - ..... - ..... - ..... - .....",
					".....", "..... - ..... - .....", ".....", ".....");
			KqGiai_Item item03 = new KqGiai_Item(code3, " TƯỜNG THUẬT", "",
					".....", ".....", ".....", "..... - .....",
					"..... - ..... - ..... - ..... - ..... - ..... - .....",
					".....", "..... - ..... - .....", ".....", ".....");

			hashtable_result = new Hashtable<String, KqGiai_Item>();
			if (!code3.equals("")) {
				hashtable_result.put(code1, item01);
				hashtable_result.put(code2, item02);
				hashtable_result.put(code3, item03);
			} else {
				hashtable_result.put(code1, item01);
				hashtable_result.put(code2, item02);
			}
		}

		startread();

		arraylist_end.clear();

		if (!code3.equals("")) {
			// UPDATE CODE
			for (int j = 0; j < push_tn.size(); j++) {
				hashtable_result.remove(push_tn.get(j).getCode());
				hashtable_result.put(push_tn.get(j).getCode(), push_tn.get(j));
			}
			arraylist_end.add(hashtable_result.get(code1));
			arraylist_end.add(hashtable_result.get(code2));
			arraylist_end.add(hashtable_result.get(code3));
			// END

		} else {
			// UPDATE CODE
			for (int j = 0; j < push_tn.size(); j++) {
				hashtable_result.remove(push_tn.get(j).getCode());
				hashtable_result.put(push_tn.get(j).getCode(), push_tn.get(j));
			}

			arraylist_end.add(hashtable_result.get(code1));
			arraylist_end.add(hashtable_result.get(code2));

			// END
		}
		// LoadData
		if (arraylist_end != null) {
			load_data_webviewTN(arraylist_end, "");
			bt_thongke.setVisibility(View.VISIBLE);
		} else {
			webView.clearCache(true);
			webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
			bt_thongke.setVisibility(View.GONE);
			Util.showDialog(1, getActivity());
		}
	}

	private boolean getArrayAudio(List<KqGiai_Item> result) throws IOException {
		if (result == null) {
			SmartLog.d("don't load result");
			return false;
		}
		boolean hasDataResource = false;
		for (int k = 0; k < result.size(); k++) {
			if (result.get(k).getCode().equals(matinh)) {
				SmartLog.d("matinh " + matinh + " code "
						+ result.get(k).getCode());
				hasDataResource = true;
				listaudio.clear();
				rngay = result.get(k).getDate().split("/")[0];
				rthang = result.get(k).getDate().split("/")[1];

				rgiaidb = result.get(k).getGiaidb().replace(".....", "");
				rgiai1 = result.get(k).getGiai1().replace(".....", "");
				rgiai2 = result.get(k).getGiai2().replace(".....", "");
				rgiai3 = result.get(k).getGiai3().replace("-.....", "");
				rgiai4 = result.get(k).getGiai4().replace("-.....", "");
				rgiai5 = result.get(k).getGiai5().replace(".....", "");
				rgiai6 = result.get(k).getGiai6().replace("-.....", "");
				rgiai7 = result.get(k).getGiai7().replace(".....", "");
				rgiai8 = result.get(k).getGiai8().replace(".....", "");

				listaudio.add("voice/Xoso/Xs_kqxs.mp3");
				listaudio.add(getProvince(matinh));
				listaudio.add("voice/Xoso/Xs_mothuong.mp3");
				listaudio.add(getDay(rngay));
				listaudio.add(getMonth(rthang));

				// giai 8
				if (rgiai8.length() > 1) {
					listaudio.add("voice/Giai/Giai_8.mp3");
					data = rgiai8.split("");
					for (int i = 1; i < data.length; i++) {
						listaudio.add(getNumber(data[i]));
					}
					listaudio.add("voice/Beep/beep-2.mp3");
				}
				// giai 7
				if (rgiai8.length() > 1 & rgiai7.length() > 1) {
					listaudio.add("voice/Giai/Giai_7.mp3");
					data = rgiai7.split("");
					for (int i = 1; i < data.length; i++) {
						listaudio.add(getNumber(data[i]));
					}
					listaudio.add("voice/Beep/beep-2.mp3");
				}
				// giai 6
				if (rgiai7.length() > 1 & rgiai6.length() > 1) {
					listaudio.add("voice/Giai/Giai_6.mp3");
					databuf = rgiai6.split("-");
					for (int j = 0; j < databuf.length; j++) {
						data = databuf[j].split("");
						for (int i = 1; i < data.length; i++) {
							listaudio.add(getNumber(data[i]));
						}
						listaudio.add("voice/Beep/beep-2.mp3");
					}
				}
				// giai 5
				if (rgiai6.split("-").length >= 3 & rgiai5.length() > 1) {
					listaudio.add("voice/Giai/Giai_5.mp3");
					data = rgiai5.split("");
					for (int i = 1; i < data.length; i++) {
						listaudio.add(getNumber(data[i]));
					}
					listaudio.add("voice/Beep/beep-2.mp3");
				}
				// giai4
				if (rgiai5.length() > 1 & rgiai4.length() > 1) {
					listaudio.add("voice/Giai/Giai_4.mp3");
					databuf = rgiai4.split("-");
					for (int j = 0; j < databuf.length; j++) {
						data = databuf[j].split("");
						for (int i = 1; i < data.length; i++) {
							listaudio.add(getNumber(data[i]));
						}
						listaudio.add("voice/Beep/beep-2.mp3");
					}
				}
				// giai3
				if (rgiai4.split("-").length >= 7 & rgiai3.length() > 1) {
					listaudio.add("voice/Giai/Giai_3.mp3");
					databuf = rgiai3.split("-");
					for (int j = 0; j < databuf.length; j++) {
						data = databuf[j].split("");
						for (int i = 1; i < data.length; i++) {
							listaudio.add(getNumber(data[i]));
						}
						listaudio.add("voice/Beep/beep-2.mp3");
					}
				}
				// giai2
				if (rgiai3.split("-").length >= 2 & rgiai2.length() > 1) {
					listaudio.add("voice/Giai/Giai_2.mp3");
					data = rgiai2.split("");
					for (int i = 1; i < data.length; i++) {
						listaudio.add(getNumber(data[i]));
					}
					listaudio.add("voice/Beep/beep-2.mp3");
				}
				// giai1
				if (rgiai2.length() > 1 & rgiai1.length() > 1) {
					listaudio.add("voice/Giai/Giai_1.mp3");
					data = rgiai1.split("");
					for (int i = 1; i < data.length; i++) {
						listaudio.add(getNumber(data[i]));
					}
					listaudio.add("voice/Beep/beep-2.mp3");
				}
				// giai db
				if (rgiai1.length() > 1 & rgiaidb.length() > 1) {
					listaudio.add("voice/Giai/Giai_Db.mp3");
					data = rgiaidb.split("");
					for (int i = 1; i < data.length; i++) {
						listaudio.add(getNumber(data[i]));
					}
					listaudio.add("voice/Beep/beep-2.mp3");
				}
				break;
			}
		}
		return hasDataResource;
	}

	public void playAudio() throws IOException {
		counter_save = Util.readFilePrivateTab(getActivity());
		String fileAudioName = listaudio.get(position);
		String fileAudioBefore = "";
		if (position > 0) {
			fileAudioBefore = listaudio.get(position - 1);
		}
		boolean isNumber = isNumber(fileAudioName);
		boolean isNumberBefore = isNumber(fileAudioBefore);
		if (isNumber) {
			String numberReading = getNumberFromPosition(position);
			if (!isNumberBefore) {
				load_data_webviewTN(itemsReading, numberReading);
			}
			SmartLog.d("number reading " + numberReading);
		}

		if (counter_save.equals("1")
				&& rgiaidb != null
				&& listaudio.size() >= position
				&& listaudio.size() > position
				&& (rgiaidb != null && rgiai1 != null && rgiai2 != null
						&& rgiai3 != null && rgiai4 != null && rgiai5 != null
						&& rgiai6 != null && rgiai7 != null && rgiai8 != null)) {
			AssetFileDescriptor fd = assets.openFd(listaudio.get(position));
			media.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(),
					fd.getLength());
			media.setAudioStreamType(AudioManager.STREAM_RING);
			media.prepare();
			isReplay = false;
			position++;
		} else {
			mPreference.setPosAudio(mCode, matinh, date_current, position);
			isReplay = true;
		}
	}

	private void startread() {
		if (media != null && /* start == 1 && */dangnghe == true) {
			media.start();
			imgPlay.setBackgroundResource(R.drawable.button_off_sound);
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		if (mLoadKQXSServerTask != null) {
			mLoadKQXSServerTask.cancel(true);
			mLoadKQXSServerTask = null;
		}
		if (myTask != null) {
			myTask.cancel(true);
			myTask = null;
		}
	}

	private String getProvince(String id) {
		return "voice/TenTinh/Tinh_" + id + ".mp3";
	}

	private String getDay(String day) {
		return "voice/Ngay/Ngay_" + day + ".mp3";
	}

	private String getMonth(String month) {
		return "voice/Thang/Thang_" + month + ".mp3";
	}

	private String getNumber(String number) {
		return "voice/So/So_" + number + ".mp3";
	}

	@SuppressWarnings("unused")
	private String getGiai(int giai) {
		return "voice/Giai/Giai_" + giai + ".mp3";
	}

	private class MyWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {

			if (isFree) {
				return false;
			}

			System.out.println("URL MIEN TRUNG LA" + url);
			db = new DataBaseHandler(getActivity());
			System.out.println("SO BAN GHI LA  " + db.getCountKq());
			item_subkq = db.getSubKq(url);
			if (item_subkq != null) {
				System.out.println("CHAY VAO 1");
				if (dayofmonth == Integer.parseInt(item_subkq.getDate())) {
					isSendSms = false;
					System.out.println("CHAY VAO 11");
				} else {
					System.out.println("CHAY VAO 12");
					db.updateSubKq(item_subkq);
					isSendSms = true;
				}
			} else {
				System.out.println("CHAY VAO 2");
				item_subkq = new SubKq_Item(url, Integer.toString(dayofmonth));
				db.insertSubKq(item_subkq);
				isSendSms = true;
			}
			if (isSendSms) {
				//
				if (nhamang.contains("VIETTEL")) {
					if (Util.onClick_MT())
						Util.sendSMS(url, "8585", getActivity());
					else
						Util.sendSMS(url, "8185", getActivity());
					Toast.makeText(getActivity(), "Đăng ký thành công!",
							Toast.LENGTH_LONG).show();
				} else {
					// Util.sendSMS("DK "+url, "8985", getActivity());
					// if(!Util.getdataSms(getActivity()," Ket Qua XSMT")&&!Util.getSharePreferencesSub(getActivity(),"subxsmt").equals("1")){
					// Util.SharedPreferencesSub("1", "subxsmt", getActivity());
					Util.sendSMS("DK XSMT", "8985", getActivity());
					Toast.makeText(getActivity(), "Đăng ký thành công!",
							Toast.LENGTH_LONG).show();
					// }else if (Util.getdataSms(getActivity()," Ket Qua XSMB"))
					// {
					// Util.SharedPreferencesSub("0", "subxsmt", getActivity());
					// }
				}
			} else {
				System.out.println("KHONG CHAY VAO IF");
				if ((!nhamang.contains("VIETTEL"))
						&& Util.getdataSms(getActivity(),
								" goi XO SO MIEN TRUNG")
						&& !Util.getSharePreferencesSub(getActivity(),
								"subxsmt").equals("1")) {
					System.out.println("HUỷe");
					Util.SharedPreferencesSub("1", "subxsmt", getActivity());
					Util.sendSMS("DK XSMT", "8985", getActivity());
					Toast.makeText(getActivity(), "Đăng ký thành công!",
							Toast.LENGTH_LONG).show();
				} else {
					System.out.println("Không có hủy");
				}
			}
			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub
			super.onPageFinished(view, url);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			// page could not be loaded
		}
	}
}
